package models

import (
	"code.sgfoot.com/sg-seehome/common"
	"github.com/astaxie/beego/orm"
)

//插入数据
func (t *Classify) Insert() error {
	t.CreatedAt = common.GetNowDateTime()
	t.UpdatedAt = common.GetNowDateTime()
	id, err := o.Insert(t)
	t.Id = int(id)
	return err
}

//检查是否重名
func (t *Classify) CheckName() bool {
	//num, err := o.Raw("select id from classify where name = ?", name).QueryRows()
	num, err := o.QueryTable(new(Classify)).Filter("type_name", t.TypeName).Filter("state", 0).Filter("parent_id", t.ParentId).Filter("user_id", t.UserId).Count()
	if err == nil && num > 0 {
		return true
	}
	return false
}

//查询父级列表
func (t *Classify) SelectParent() (rs []orm.Params, err error) {
	num, err := o.Raw("select * from classify where state = 0 and parent_id = 0").Values(&rs)
	if err == nil && num > 0 {
		return
	}
	return nil, err
}

//查询子项
func (t *Classify) SelectChild(parentId int) (rs []orm.Params, err error) {
	num, err := o.Raw("select * from classify where state = 0 and parent_id = ?", parentId).Values(&rs)
	if err == nil && num > 0 {
		return
	}
	return nil, err
}

//查询所有数据
func (t *Classify) Select(userId int) (rs []orm.Params, err error) {
	num, err := o.Raw("select * from classify where state = 0 and user_id in (0, ?) limit 1000", userId).Values(&rs)
	if err == nil && num > 0 {
		return
	}
	return nil, err
}
